package com.cennavi.minemap.tool;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cennavi.minemap.util.GeoUtil;
import com.alibaba.fastjson.JSONObject;
import com.cennavi.minemap.dao.UploadDao2;
import com.vividsolutions.jts.geom.Geometry;

public class ParseJsonFile implements ParseFile {

	@Override
	public Map<String,Integer> parse(String fullPath, UploadDao2 uploadDao, int type, int userId, int uploadId) {
		// TODO Auto-generated method stub
		FileReader fr = null;
		try {
			fr = new FileReader(fullPath);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		BufferedReader bufferedReader = new BufferedReader(fr);
		
		
		Map<String,Integer> rMap = new HashMap<>();
		
		String line;
		List<Map<String, Object>> list = new ArrayList<>();
		int succLine = 0;
		int fileLine = 0;
		try {
			//uploadDao.createUploadDetail(userId, uploadId);
			while ((line = bufferedReader.readLine()) != null) {
				if (0 != line.length()) {
					fileLine++;
					JSONObject json = JSONObject.parseObject(line.trim());

					String geometry = json.getJSONObject("geometry").toJSONString();
					String properties = json.getJSONObject("properties").toJSONString();

					Geometry geom = null;
					String geomStr = null;

					try {
						geom = GeoUtil.readGeojson(geometry);
						geomStr = GeoUtil.geometry2WKT(geom);
					} catch (Exception e) {
						e.printStackTrace();
					}

					Map<String, Object> map = new HashMap<>();
					map.put("uploadId", uploadId);
					map.put("attr", properties);
					map.put("geom", geomStr);
					list.add(map);
					if (list.size() == 1000) {
						succLine = succLine + list.size();
						uploadDao.addUploadDetail(list, userId, uploadId);
						list.clear();
					}
				}
			}
			
			if (list.size() > 0) {
				succLine = succLine + list.size();
				uploadDao.addUploadDetail(list, userId, uploadId);
			}

			rMap.put("fileLine", fileLine);
			rMap.put("succLine", succLine);
			
			fr.close();
			
			return rMap;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

}
